using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SqlServer.Management.UI.VSIntegration;
using Microsoft.SqlServer.Management.UI.VSIntegration.Editors;
using Microsoft.SqlServer.Management.Smo.RegSvrEnum;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer;
using System.Data.SqlClient;
using System.Data;
using Logger;

namespace Tools
{
    public class UtilitySqlTools
    {
        static UtilitySqlTools currentInstance = new UtilitySqlTools();

        private UIConnectionInfo currentUIConnection;
        private SqlConnectionInfo currentConnection;

        public static UtilitySqlTools Current
        {
            get { return currentInstance; }
        }

        private SqlConnectionInfo CreateSqlConnectionInfo(UIConnectionInfo connectionInfo)
        {
            SqlConnectionInfo sqlConnInfo = new SqlConnectionInfo();
            sqlConnInfo.ServerName = connectionInfo.ServerName;
            sqlConnInfo.UserName = connectionInfo.UserName;
            if (string.IsNullOrEmpty(connectionInfo.Password))
            {
                sqlConnInfo.UseIntegratedSecurity = true;
            }
            else
            {
                sqlConnInfo.Password = connectionInfo.Password;
            }

            return sqlConnInfo;
        }

        public SqlConnectionInfo GetActiveWindowConnection()
        {
            SqlConnectionInfo info = null;
            try
            {
                UIConnectionInfo connInfo = null;
                if (ServiceCache.ScriptFactory.CurrentlyActiveWndConnectionInfo != null)
                {
                    connInfo = ServiceCache.ScriptFactory.CurrentlyActiveWndConnectionInfo.UIConnectionInfo;
                }
                if (connInfo != null)
                {
                    if (connInfo == currentUIConnection)
                    {
                        return currentConnection;
                    }
                    else
                    {
                        info = CreateSqlConnectionInfo(connInfo);
                        currentConnection = info;
                        currentUIConnection = connInfo;
                    }
                }
                if (info == null)
                {
                    // attempt to get connection info from node in tree view
                    INodeInformation[] nodes = GetObjectExplorerSelectedNodes();
                    if (nodes.Length > 0)
                    {
                        info = nodes[0].Connection as SqlConnectionInfo;
                    }
                }
                return info;
            }
            catch (NullReferenceException)
            {
                return null;
            }
        }

        public string ConnectionString()
        {
            if (GetActiveWindowConnection() != null)
                return GetActiveWindowConnection().ConnectionString;
            else
                return null;
        }

        private INodeInformation[] GetObjectExplorerSelectedNodes()
        {
            IObjectExplorerService objExplorer = ServiceCache.GetObjectExplorer();
            int arraySize;
            INodeInformation[] nodes;
            objExplorer.GetSelectedNodes(out arraySize, out nodes);
            return nodes;
        }

        public static void EnableDisableBroker(string current_database, SqlConnection connection, bool enabled)
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("USE [" + current_database + "];");
            sb.Append("ALTER DATABASE [" + current_database + "]");
            if (enabled)
            {
                sb.Append(" SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE");
            }
            else
            {
                sb.Append(" SET DISABLE_BROKER WITH ROLLBACK IMMEDIATE");
            }

            try
            {
                SqlCommand command = new SqlCommand();
                command.CommandText = sb.ToString();
                command.CommandTimeout = 0;
                command.CommandType = CommandType.Text;
                command.Connection = connection;
                command.ExecuteNonQuery();
            }
            catch (Exception exception)
            {
                LoggerWriter.Current.WriteError(exception.Message);
            }
        }


    }
}
